package com.example.demo.service.impl;

import com.example.demo.dto.RoleDto;
import com.example.demo.dto.RoleSmallDto;
import com.example.demo.dto.UserDto;
import com.example.demo.entity.Menu;
import com.example.demo.entity.Role;
import com.example.demo.entity.User;
import com.example.demo.mapper.RoleMapper;
import com.example.demo.mapper.RoleSmallMapper;
import com.example.demo.repository.RoleRepository;
import com.example.demo.repository.UserRepository;
import com.example.demo.service.RoleService;
import com.example.demo.utils.StringUtils;
import com.example.demo.utils.ValidationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@CacheConfig(cacheNames = "role")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RoleSmallMapper roleSmallMapper;

    @Override
    @Cacheable(key = "#p0")
    public RoleDto findById(long id) {
        Role role = roleRepository.findById(id).orElseGet(Role::new);
        ValidationUtil.isNull(role.getId(),"Role","id",id);
        return roleMapper.toDto(role);
    }

    @Override
    @Cacheable(key = "'findByUsers_Id:' + #p0")
    public List<RoleSmallDto> findByUsersId(Long id) {
        User user=userRepository.findById(id).orElseGet(User::new);
        Role role = roleRepository.findById(user.getRoleId()).orElseGet(Role::new);
        Set<Role> roles = new HashSet<>();
        roles.add(role);
        return roleSmallMapper.toDto(new ArrayList<>(roles));
    }

    @Override
    @Cacheable
    public Integer findByRoleId(Long roleId) {
        RoleDto roleDto = findById(roleId);
        return roleDto.getLevel();
    }

    @Override
    @Cacheable(key = "'loadPermissionByUser:' + #p0.userName")
    public Collection<GrantedAuthority> mapToGrantedAuthorities(UserDto user) {
        Role rolee = roleRepository.findById(user.getRoleId()).orElseGet(Role::new);
        Set<Role> roles = new HashSet<>();
        roles.add(rolee);
        Set<String> permissions = new HashSet<>();
        permissions.addAll(
                roles.stream().flatMap(role -> role.getMenus().stream())
                        .filter(menu -> StringUtils.isNotBlank(menu.getPermission()))
                        .map(Menu::getPermission).collect(Collectors.toSet())
        );
        return permissions.stream().map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
    }


}
